package com.joysuch.wwyt.quartz.workflow;

import com.joysuch.wwyt.workflow.entity.WorkFlowProcessCodeStrategy;
import com.joysuch.wwyt.workflow.enums.WorkFlowCodeStrategyEnum;
import com.joysuch.wwyt.workflow.repository.WorkFlowProcessCodeStrategyDao;
import com.joysuch.wwyt.workflow.service.WorkFlowProcessScheduleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author ZhaoQiuWei
 * @Date 2021/5/30 0:06
 */

@Slf4j
@Service
public class WorkFlowProcessSchedule implements WorkFlowProcessScheduleService {
    @Autowired
    private WorkFlowProcessCodeStrategyDao workFlowProcessCodeStrategyDao;

    @Override
    public void codeStrategyUpdateJob(Integer flag) {
        if (WorkFlowCodeStrategyEnum.DAY.is(flag)) {
            this.dayData();
        } else if (WorkFlowCodeStrategyEnum.MONTH.is(flag)) {
            this.monthData();
        } else if (WorkFlowCodeStrategyEnum.YEAR.is(flag)) {
            this.yearData();
        }
    }

    @Scheduled(cron = "0 0 0 * * ?")
    private void codeStrategyDayJob() {
        this.dayData();
    }

    private void dayData() {
        List<WorkFlowProcessCodeStrategy> strategyList = workFlowProcessCodeStrategyDao.findByCodeStrategy(WorkFlowCodeStrategyEnum.DAY.getIndex());
        this.updateBizCodeTypeNumber(strategyList);
    }

    @Scheduled(cron = "0 0 0 1 * ?")
    private void codeStrategyMonthJob() {
        this.monthData();
    }

    private void monthData() {
        List<WorkFlowProcessCodeStrategy> strategyList = workFlowProcessCodeStrategyDao.findByCodeStrategy(WorkFlowCodeStrategyEnum.MONTH.getIndex());
        this.updateBizCodeTypeNumber(strategyList);
    }

    @Scheduled(cron = "59 59 23 31 12 ?")
    private void codeStrategyYearJob() {
        this.yearData();
    }

    private void yearData() {
        List<WorkFlowProcessCodeStrategy> strategyList = workFlowProcessCodeStrategyDao.findByCodeStrategy(WorkFlowCodeStrategyEnum.YEAR.getIndex());
        this.updateBizCodeTypeNumber(strategyList);
    }

    private void updateBizCodeTypeNumber(List<WorkFlowProcessCodeStrategy> strategyList) {
        if (!CollectionUtils.isEmpty(strategyList)) {
            workFlowProcessCodeStrategyDao.updateBizNumberByIds(1, strategyList.stream().map(e -> e.getId()).collect(Collectors.toList()));
        }
    }
}
